<?php
/**
 * Created by PhpStorm.
 * User: lcz
 * Date: 2018/4/3
 * Time: 10:40
 * 购物车
 */

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

class Cart extends Api{
	protected $noNeedRight = ['*'];
	
	/**
	 * 购物车列表
	 */
	public function index(){
		$uid = $this->auth->id;
		$model = new \app\common\model\Cart();
		
		$list = Db::name('cart')->alias('c')
			->join('goods g', 'c.goods_id = g.id', 'left')
			->join('goods_spec_price p', 'c.price_id = p.id', 'left')
			->join('business b', 'g.business_id = b.id', 'left')
			->field('c.id, c.id as cart_id, c.number, c.update_time, c.goods_id, c.price_id, g.goods_name, g.original_image, p.spec_name,b.name as business_name, g.business_id as seller_id, g.shop_price, g.store_count, p.price, p.store_count as spec_store, g.use_point as point, g.give_balance as sendmoney')
			->order('c.update_time DESC')
			->where(['c.status' => $model::STATUS_Y, 'c.user_id' => $uid])
			->select();
		
		$seller = [];
		if($list) {
			foreach($list as $value){
				$bid = $value['seller_id'];
				if(!$value['price_id']){
					$value['price'] = $value['shop_price'];
				} else {
					$value['store_count'] = $value['spec_store'];
				}
				unset($value['spec_store']);
				if(isset($seller[$bid])){
					$seller[$bid]['products'][] = $value;
				} else {
					$seller[$bid] = [
						'seller_id' => $bid,
						'seller_name' => $value['business_name'],
						'products' => [
							$value
						]
					];
				}
			}
		}
		
		$goodsModel = new \app\common\model\Goods();
		$recommendGoods = Db::name('goods')
			->where([
				'is_on_sale' => $goodsModel::IS_ON_SALE_Y,
				'is_recommend' => $goodsModel::RECOMMEND_Y,
				'effective_time' => ['elt', time()]
				])
			->order(['sort' => 'ASC'])
			->field('id, goods_name, original_image, shop_price, market_price, sale_number, exchange_integral, use_point as point, give_balance as sendmoney')
			->limit(20)
			->select();
		
		$return = [
			'seller' => array_values($seller),
			'recommend' => $recommendGoods
		];
		$this->success('查询成功', $return);
		
	}
	
	/**
	 * 添加购物车
	 */
	public function addCart(){
		$postData = input('post.');
		$validate = validate('cart');
		if(!$validate->check($postData)){
			$this->error($validate->getError());
		}
		
		$goods = Db::name('goods')->find($postData['goods_id']);
		if(!$goods){
			$this->error('商品不存在');
		}
		
		if($goods['is_on_sale'] != 1){
			$this->error('该商品已经下架');
		}
		
		if($goods['goods_type'] != \app\common\model\Goods::GOODS_TYPE_1) {
			$this->error('该商品不支持加入购物车');
		}
		
		$storeCount = $goods['store_count'];
		$uid = $this->auth->id;
		if(isset($postData['price_id']) && !empty($postData['price_id'])){
			$spec = Db::name('goodsSpecPrice')->where(['id' => $postData['price_id'], 'goods_id' => $postData['goods_id']])->find($postData['price_id']);
			if(!$spec){
				$this->error('商品规格不存在');
			}
			$storeCount = $spec['store_count'];
		} else {
			$spec = Db::name('goodsSpecPrice')->where(['goods_id' => $postData['goods_id']])->find();
			if($spec){
				$this->error('请选择商品规格');
			}
		}
		
		if($postData['number'] > $storeCount){
			$this->error('库存不足');
		}
		$model = new \app\common\model\Cart();
	
		$where = ['user_id' => $uid, 'goods_id' => $postData['goods_id'], 'price_id' => $postData['price_id'], 'status' => $model::STATUS_Y];
		//查找是否已经添加了
		$row = $model->where($where)->find();
		if($row) {
			$newNumber = $row['number'] + $postData['number'];
			if($newNumber > $storeCount){
				$this->error('库存不足');
			}
			
			$res = $model->save(['number' => $newNumber], $where);
		} else {
			$postData['user_id'] = $uid;
			$res = $model->isUpdate(false)->allowField(true)->save($postData);
		}
		
		if($res !== false){
			$this->success('添加成功');
		} else {
			$this->success('添加出错，请稍候重试');
		}
		
	}
	
	/**
	 * 编辑购物车
	 */
	public function editCart(){
		$id = input('post.id');
		if(!$id){
			$this->error('请选择要操作的数据');
		}
		
		$number = input('post.number','','int');
		if(!$number || $number < 1){
			$this->error('数量不能为空');
		}
		
		$model = new \app\common\model\Cart();
		$uid = $this->auth->id;
		$res  = $model->save(['number' => $number], ['id' => $id, 'user_id' => $uid]);
		if($res === false){
			$this->error('操作出错，请稍候重试');
		} else {
			$this->success('修改成功');
		}
	}
	
	/**
	 * 删除购物车
	 */
	public function delCart(){
		$ids = input('post.id');
		if(!$ids){
			$this->error('请选择要删除的数据');
		}
		
		$ids = explode(',', $ids);
		$model = new \app\common\model\Cart();
		
		$uid = $this->auth->id;
		
		$res = $model->save(['status' => $model::STATUS_DEL],['id' => ['in', $ids], 'user_id' => $uid]);
		if($res !== false){
			$this->success('删除成功');
		} else {
			$this->error('删除出错，请稍候重试');
		}
	}
}
